package org.eclipse.stp.policy_builder.model.source;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.stp.policy_builder.model.AbstractSourceProvider;
import org.eclipse.stp.policy_builder.model.ISource;
import org.eclipse.stp.policy_builder.model.exceptions.DescriptorException;

public class SourceType {

	//private final static String TAG_SOURCE = "source" ;
	//private final static String TAG_PARAM = "parameter" ;
	//private final static String ATT_ID = "id" ; 
	public final static String ATT_NAME = "name" ;
	public final static String ATT_DESC = "description" ;
	public final static String ATT_CLASS = "class" ;
	private final IConfigurationElement configElement;
	private final ParameterMap params = new ParameterMap();
	
	private String id;
	private String name;
	private String className;
	private String description;
	private AbstractSourceProvider providerFactory;
	public SourceType(IConfigurationElement config)throws DescriptorException{
		this.configElement = config ;
		//this.id = getAttribute(configElement, ATT_ID, null);
		this.name = getAttribute(configElement, ATT_NAME, null);
		this.className = getAttribute(configElement, ATT_CLASS, null);
		this.description = getAttribute(configElement, ATT_DESC, "No description found.");
		
		//System.out.println("name : " + this.name);
	}
	
	private static String getAttribute(IConfigurationElement element,String attType,String valueDef)throws DescriptorException{
		String value = element.getAttribute(attType);
		if(value != null){
			return value;
		}
		else if(valueDef!=null){
			return valueDef;
		}
		
		throw new DescriptorException("Attribute [" + attType +"] is not found in the descriptor element ");
	}
	
	
	@Deprecated
	public String getID(){
		return id ;
	}
	
	public String getName(){
		return name ;
	}
	
	public String getDescription(){
		return description ;
	}
	
	public String getClassName(){
		return className ;
	}
	
	public ISource loadSource(ParameterMap params){
		AbstractSourceProvider provider = getProvider();
		if(provider!=null){
			return provider.loadSource(params);
		}
		return null;
	}
	
	private AbstractSourceProvider getProvider(){
		if(providerFactory!=null){
			return  providerFactory;
		}
		else {
			try {
				providerFactory = (AbstractSourceProvider) configElement.createExecutableExtension(ATT_CLASS);
			
			} catch (CoreException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		return providerFactory ;
	}
	
	public ParameterMap getParameterContainer(){
		
		return params;
	}
}
